package com.chenfan.mcn.controller;

import com.chenfan.common.exception.BusinessException;
import com.chenfan.mcn.annotations.ActionTracing;
import com.chenfan.mcn.enums.OperateLockEnum;
import com.chenfan.mcn.exception.McnErrorCode;
import com.chenfan.mcn.extension.Res;
import com.chenfan.common.extension.validation.groups.Add;
import com.chenfan.common.extension.validation.groups.Modify;
import com.chenfan.common.extension.lock.DistributedLockTemplate;
import com.chenfan.mcn.model.dto.IncomeAgreementAddDTO;
import com.chenfan.mcn.service.IncomeContactAgreementService;
import com.chenfan.privilege.common.config.UrlAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

/**
 * 收入合同补充协议
 * @author tangwei
 * Date:     2021/1/26 10:11
 * Description: 收入合同补充协议
 */
@RestController
@RequestMapping("/contract/agreement")
public class IncomeContactAgreementController {

    @Autowired
    private IncomeContactAgreementService incomeContactAgreementService;

    /**
     * 新增
     * @param agreementAddDTO
     * @return
     */
    @ActionTracing("新增收入合同补充协议")
    @PostMapping("/add")
    @UrlAuth({"revenueContract_addSupplement"})
    public Res<Boolean> add(@RequestBody @Validated({Add.class}) IncomeAgreementAddDTO agreementAddDTO) {
        return Res.ok(incomeContactAgreementService.saveAgreement(agreementAddDTO));
    }

    /**
     * 修改
     * @param agreementAddDTO
     * @return
     */
    @ActionTracing("修改收入合同补充协议")
    @PostMapping("/update")
    public Res<Boolean> update(@RequestBody @Validated({Modify.class}) IncomeAgreementAddDTO agreementAddDTO) {
        return DistributedLockTemplate.execute(OperateLockEnum.INCOME_CONTRACT_AGREEMENT.generateKey(agreementAddDTO.getId()), () ->
                Res.ok(incomeContactAgreementService.saveAgreement(agreementAddDTO)));
    }

    /**
     * 修改单据状态
     *
     * @param agreementId    {@link Long}
     * @param approvalStatus {@link Integer}
     * @return {@link Res<Object>}
     */
    @ActionTracing("收入合同补充协议-修改状态")
    @GetMapping("/changeStatus")
    @UrlAuth({"revenueContract_supplement_withdraw","revenueContract_supplement_toVoid","revenueContract_supplement_submit"})
    public Res<Object> changeStatus(@RequestParam Long agreementId, @RequestParam Integer approvalStatus) {
        if (Objects.isNull(agreementId) || Objects.isNull(approvalStatus)) {
            throw new BusinessException(McnErrorCode.PARAM_ERROR);
        }
        return Res.ok(incomeContactAgreementService.changeStatus(agreementId, approvalStatus));
    }
}
